var auto_status = null;
var auto_video = null;
(function(window) {

	/**
	 * pcc2
	 * @type {Object}
	 */
	var pcc2 = {
		$c: null,
		$space: null,
		$pages: null,
		$video: null,
		$pdfZone: null,
		$cover: null,
		scale: 1,
		isHand: false,
		connected: false
	};
	pcc2.init = function() {
	
		// 0.变量初始化
		pcc2.$c = $('#container');
		pcc2.$space = $('#space');
		pcc2.$pages = pcc2.$c.children('.pages');
		pcc2.$cover = $('#cover');
		// pcc2.$video = pcc2.$c.children('.video-zoon');

		// 0.init kpi
		kpi.init();
		// 1.重置container大小
		var width = window.innerWidth || document.documentElement.clientWidth;
		var height = window.innerHeight || document.documentElement.clientHeight;
		var scale = pcc2.scale = Math.min(width / 1920, height / 1080);
		pcc2.$c.transition({
			scale: scale
		}, 0);
		// pcc2.$c.css('zoom', scale);

		// 1.1.创建effect
		effect.onCreate();

		// 1.2.根据url设置debug
		config.debug = (location.search.indexOf('debug') != -1);
		pcc2.setDebug();

		// 1.3.是否启用摄像头
		if (!config.ondebug('noCamera')) {
			initMagic();
		}

		// 1.4.初始化socket.io
		if (!config.ondebug('noSocket'))
			pcc2.so.init();

		// 2.加载资源
		loader.load(function() {
			// 3.初始化页面
			pf.init();
			pcc2.setLang();
			// 3.0.5
			icons.init();
			// 3.1初始化effect
			// 4.进入页面
			pcc2.$pages.show();

			// pf.goPage('detail', {detailID: 'principle'});
			// pf.goPage('show', {showID: 'wdy'});
			pf.goPage('status');
			var kpi_pcc2 = {};

			// pf.goPage('topic');
			// pf.overlay('image', {imgID: 'testdrive'});
			// pf.goPage('show', {showID: 'wdy'});
			// pf.goPage('home', {detailID: 'wdy'});
			// pf.goPage('detail', {detailID: 'principle'});
			// pf.goPage('movie');
			// if(!config.ondebug('noPreload'))
			// pf.goPage('movie');
			// pf.goPage('status');
			// pf.goPage('detail', {detailID:"911"});
			// pf.goPage("vehicleList");
			// pf.goPage('topic', {showID: 'wdy'});

			// pcc2.pdf();
			$(document).find('.porsche_logo').click(function(event) {
				pf.goPage('status');
				// so.emit('disconnect');
			});
			$(document).click(function() {
				window.clearTimeout(auto_video);
				auto_video=window.setTimeout(function(){
					window.clearTimeout(auto_status);
					window.clearTimeout(so.backTimer);
					if ($("#play_video").is(":hidden")){
						if(!$('#features').hasClass('test_video_now')){
							if(!$('#image').hasClass('test_video_now')){
								auto_status = window.setTimeout(function() {
									if ($('#status').css("display") == "none") {
										pf.goPage('status');
										so.emit('disconnect');
									}
								},config.auto);
							}else{
								auto_status = window.setTimeout(function() {
									if ($('#status').css("display") == "none") {
										pf.goPage('status');
										so.emit('disconnect');
									}
								}, config.auto_more_than);
							};
						}else{
							auto_status = window.setTimeout(function() {
								if ($('#status').css("display") == "none") {
									pf.goPage('status');
									so.emit('disconnect');
								}
							}, config.auto_more_than);
						};
					}else{
						auto_status = window.setTimeout(function() {
							if ($('#status').css("display") == "none") {
								pf.goPage('status');
								so.emit('disconnect');
							}
						}, config.auto_more_than);
					}
				},1000);
			});
		});
	};

	pcc2.hidepdf = function() {
		pcc2.$pdfZone && pcc2.$pdfZone.hide();
	};

	pcc2.light = function(flag,c) {
		$.post(config.lightUrl, {
			outletId: c,
			outletStatus: flag
		});
	};
	pcc2.pdf = function() {
		if (pcc2.$pdfZone) {
			pcc2.$pdfZone.show();
		} else {
			pcc2.$pdfZone = $('#viewerContainer').show();

			var DEFAULT_URL = './catalog.pdf';
			PDFJS.workerSrc = './pdf/pdf.worker.js';

			var container = document.getElementById('viewerContainer');
			var pdfViewer = new PDFJS.PDFViewer({
				container: container
			});

			container.addEventListener('pagesinit', function() {
				// we can use pdfViewer now, e.g. let's change default scale.
				pdfViewer.currentScaleValue = 'page-width';
				// pdfViewer.currentScaleValue = 0.6;
			});

			// Loading document.
			PDFJS.getDocument(DEFAULT_URL).then(function(pdfDocument) {
				// Document loaded, specifying document for the viewer.
				pdfViewer.setDocument(pdfDocument);
			});
		}
	};

	var goToQr = window.goToQr = function() {
		pf.pages.status.$el.click();
	};

	pcc2.setLang = function() {
		var lang = i18n.getLang();
		if (!pcc2.$c.hasClass(lang))
			pcc2.$c.removeClass('en zh-cn').addClass(lang);
	};
	pcc2.css3 = function(parmas) {
		if ($(parmas).css("opacity") !== "1") {
			return false;
		};
		$(parmas).addClass("after_1");
		// window.setTimeout(function() {
		$(parmas).addClass("after_2");
		// }, 200);
		// window.setTimeout(function() {
		if ($("body").hasClass("white_border")) {
			$(parmas).addClass("after_4");
		} else {
			$(parmas).addClass("after_3");
		}
		// }, 300);
		window.setTimeout(function() {
			$(parmas).removeClass("after_1");
			$(parmas).removeClass("after_2");
			// if ($(document).hasClass("after_4")) {
			$(parmas).removeClass("after_4");
			$(parmas).removeClass("after_3");

			// };
			// if ($(document).hasClass("after_3")) {
			// };
		}, 1000);
	}
	pcc2.switchLang = function() {
		var lang = i18n.getLang();
		// alert(1);
		i18n.setLang(lang == 'en' ? 'zh-cn' : 'en');
		pcc2.setLang();
		pcc2.$c.find('.i18n-word').each(function() {
			var k = $(this).data('langkey');
			$(this).replaceWith(i18n.get(k));
		});
	};
	pcc2.video_close_detail = function() {
		$("body").removeClass("white_border");
		pcc2.css3(".closeVieoBtn .x_video");
		window.setTimeout(function() {
			pcc2.$video.fadeOut();
			pcc2.$video.empty();
			var myVideo = document.getElementsByTagName('video')[0];
			if (myVideo) {
				myVideo.play();
			}
		}, 500);
	}
	pcc2.getTpl = function(tplID) {
		return loader.tpls[tplID];
	};
	pcc2.setDebug = function() {
		if (config.debug) {

		} else {
			$('body').attr('oncontextmenu', 'return false;');
			$('body').attr('onselectstart', 'return false;');
		}
	};
	pcc2.eventTester = function(){
		var Media = document.getElementById("media"); 
	     Media.addEventListener("ended",function(){
	         $(".operate-zoon.overlay").find('.icon-btn.sprite.close_b').click();
	     },false);
	 }
	pcc2.playVideo = function(url) {

		$("body").addClass("white_border");
		pcc2.$video.fadeIn();
		// pcc2.$video.empty();
		// localStorage.clear();
		// for(i=0;i<document.getElementsByTagName('video').length;i++){
		// 	document.getElementsByTagName('video')[i].pause();
		// }
		var myVideo = document.getElementsByTagName('video')[0];
		if (myVideo) {
			myVideo.pause();
		};
		var videoTpl = '<video id="media"  class="vide_id video_black" style="  width: 100%;height: 100%;" autoplay="autoplay"><source src="%s" type="video/mp4" /></video><div class="closeVieoBtn "><div class="icon-btn x_video  close_b"><div style="width:81px;height:81px;" class="icon-btn sprite close_b"></div></div></div>';
		pcc2.$video.append(util.format(videoTpl, url));
		pcc2.eventTester()
	};

	var so = pcc2.so = {
		socket: null,
		backTimer: null
	};
	so.init = function() {
		so.socket = io.connect(config.socketUrl + '/iScreen-socket');

		so.socket.on('control.connected', function(data) {
			if (pcc2.isHand) return;

			console.warn('control.connected', data);

			window.clearTimeout(so.backTimer);
			window.clearTimeout(auto_status);
			pcc2.connected = true;

			// test
			pf.goPage('show', {
				showID: 'wdy',
				force: true
			});
			// pf.goPage('movie');

			kpi.store('entrance', 'remote');
			pcc2.$cover.show();
		});

		so.socket.on('control.disconnect', function(data) {
			if (pcc2.isHand) return;

			pcc2.connected = false;
			so.backTimer = window.setTimeout(function() {
				pf.goPage('status');

				window.clearTimeout(so.backTimer);
				window.clearTimeout(auto_status);
			}, 3000);
		});

		// c操作o.5
		so.socket.on('control.operate', function(data) {
			if (pcc2.isHand) return;

			console.warn('control.operate', data);
			switch (data.action) {
				case 'clickBtn':
					pf.onControlClick(data);
					break;
			}
		});
	};
	so.emit = function(action, data) {
		data = data || {};
		data.action = action || '';
		so.socket.emit('screen.operate', data);
	};

	/**
	 * 加载器
	 * @type {Object}
	 */
	var loader = pcc2._loader = {
		imgres: [],
		tplres: [],
		tpls: {}
	};
	loader.load = function(cb) {
		var imgs = loader.imgres = _IMAGES_RES || [];
		var tpls = loader.tplres = _TPL_RES || [];

		// 0.加载图片
		var loadImg = function() {
			var renderRate = effect.loading(cb);
			var allSize = _ALL_SIZE;
			var size = 0;

			var deferred = when.defer();
			var imglen = imgs.length;
			for (var i in imgs) {
				(function(i) {
					var img = new Image();
					img.onload = function() {
						size += imgs[i]['size'];
						renderRate(size / allSize);

						if (--imglen <= 0) {
							deferred.resolve();
						}
					};
					img.src = imgs[i]['src'];
				})(i);
			}
			return deferred.promise;
		};

		// 1.加载tpl
		var loadTpl = function() {
			var deferred = when.defer();
			var tpllen = tpls.length;
			for (var i in tpls) {
				(function(i) {
					$.get(tpls[i]['src'] + '?' + Math.random(), function(html) {
						loader.tpls[tpls[i]['id']] = html;

						if (--tpllen <= 0) {
							deferred.resolve();
						}
					});
				})(i);
			}
			return deferred.promise;
		};
		if (!config.debug) {
			loadTpl = function() {
				var deferred = when.defer();
				for (var i in tpls) {
					loader.tpls[tpls[i]['id']] = tpls[i]['data'];
				}
				deferred.resolve();
				return deferred.promise;
			};
		}

		loadTpl().then(loadImg);
		// when.settle([loadImg(), loadTpl()]).then(cb);
	};

	$(function() {
		window.setTimeout(pcc2.init, 200);

	});

	window.pcc2 = pcc2;
})(window);